package com.heima.search.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.behavior.IBehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.mapper.ApUserSearchMapper;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.ApThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Transactional
@Service
@Slf4j
public class ApUserSearchServiceImpl extends ServiceImpl<ApUserSearchMapper, ApUserSearch> implements ApUserSearchService {


    @Async("taskExecutor")
    @Override
    public void insert(Integer entryId, String keyword) {
        //1.参数校验
        if(entryId==null || StringUtils.isEmpty(keyword)){
            log.info("[异步记录搜索关键词] 参数有误");
            return;
        }

        //2.查询搜素记录（通过entryId和keyword）
        ApUserSearch apUserSearch = getOne(Wrappers.<ApUserSearch>lambdaQuery().eq(ApUserSearch::getEntryId, entryId).eq(ApUserSearch::getKeyword, keyword));

        //3.判断如果不存在，就创建
        if(apUserSearch==null){
            apUserSearch = new ApUserSearch();
            apUserSearch.setEntryId(entryId);//行为实体ID
            apUserSearch.setKeyword(keyword);//搜索关键词
            apUserSearch.setStatus(1); //有效
            apUserSearch.setCreatedTime(new Date());
            save(apUserSearch);

        } else {
            //4.如果存在且状态为1，则忽略
            if(apUserSearch.getStatus()==1){
                log.info("[异步记录搜索关键词]关键词已保存过");
                return;
            } else {
                //5.如果存在且状态为0，则改为1
                ApUserSearch apUserSearchDB = new ApUserSearch();
                apUserSearchDB.setId(apUserSearch.getId());
                apUserSearchDB.setStatus(1); //更新为有效状态
                updateById(apUserSearchDB);
            }
        }
    }

    @Autowired
    private IBehaviorFeign behaviorFeign;


    @Override
    public ResponseResult load(UserSearchDto dto) {
        //1.判断参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断行为实体是否存在
        Integer userId = null;
        ApUser user = ApThreadLocalUtils.getUser();
        if(user!=null && user.getId()>0){
            userId = user.getId();
        }

        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdAndEquipmentId(userId, dto.getEquipmentId());
        if(apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体不存在");
        }


        //3.分页查询数据，查询条件：实体ID、状态为1， 结果：时间倒排，限制5条
        LambdaQueryWrapper<ApUserSearch> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(ApUserSearch::getEntryId, apBehaviorEntry.getId());//行为实体ID
        lambdaQueryWrapper.eq(ApUserSearch::getStatus, 1); //有效状态
        lambdaQueryWrapper.orderByDesc(ApUserSearch::getCreatedTime); //按照时间倒排

        if(dto.getPageSize()>5){
            dto.setPageSize(5); //不超5条
        }

        Page<ApUserSearch> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        this.page(page,lambdaQueryWrapper);

        //4.响应数据
        ResponseResult responseResult = new PageResponseResult(dto.getPageNum(),dto.getPageSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }


    @Override
    public ResponseResult del(UserSearchDto dto) {
        //1.判断参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断行为实体是否存在
        Integer userId = null;
        ApUser user = ApThreadLocalUtils.getUser();
        if(user!=null && user.getId()>0){
            userId = user.getId();
        }

        ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdAndEquipmentId(userId, dto.getEquipmentId());
        if(apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体不存在");
        }

        //3.判断搜索记录是否存在
        ApUserSearch apUserSearch = getById(dto.getId());
        if(apUserSearch==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "搜索记录不存在");
        }

        //4.如果已删除过，则响应错误码
        if(apUserSearch.getStatus()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIC_ERROR, "数据已删除过");
        }

        //5.执行更新
        ApUserSearch apUserSearchDB = new ApUserSearch();
        apUserSearchDB.setId(dto.getId());
        apUserSearchDB.setStatus(0); //设置为无效（逻辑删除）
        updateById(apUserSearchDB);

        //6.响应结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
